package com.qf.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @Author:YuhuaZhang
 * @Description
 * @Date:Created in 9:31 2021/10/21
 * @Modified By:
 */
public class DBUtil {
    private static final Properties PRO=new Properties();
    private static ThreadLocal<Connection> threadLocal=new ThreadLocal<>();
    static {

        InputStream is=DBUtil.class.getResourceAsStream("/jdbc.properties");
        try {
            PRO.load(is);
            //1.加载驱动
            Class.forName(PRO.getProperty("driver"));

        } catch (ClassNotFoundException | IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接的方法
     * @return con
     */
    public static Connection getConnection() {
        //将当前线程中绑定的Connection对象，赋值给connection
        Connection con = threadLocal.get();
        try {
            if (con==null) {
                con = DriverManager.getConnection(PRO.getProperty("url"), PRO.getProperty("username"), PRO.getProperty("password"));
                //把连接存在当前线程共享中
                threadLocal.set(con);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
    }


    /**
     * 关闭对象，释放资源的方法
     * @param con
     * @param ps
     * @param rs
     */
    public static void closeAll(Connection con, PreparedStatement ps, ResultSet rs){
        try {
            if (rs!=null){
                rs.close();
            }
            if (ps!=null){
                ps.close();
            }
            if (con!=null){
                con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}